//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/page/resource_page_model.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/subject/note_vo_model.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/question/note_add_widget.dart';
import 'package:hktk_app/widget/question/note_item_widget.dart';
import 'package:hktk_app/widget/question/note_list_widget.dart';

/// 做题笔记显示组件
class StemNoteWidget extends StatefulWidget {
  /// 试题id
  final String qId;

  /// 关联id，章节/试卷等id
  final String relationId;

  /// 关联名称
  final String relationName;

  /// 题干冗余
  final List<Stem> stem;

  /// 类型
  final CollectionTypeEnum type;

  const StemNoteWidget({
    super.key,
    required this.qId,
    required this.relationId,
    required this.relationName,
    required this.stem,
    required this.type,
  });

  @override
  State<StemNoteWidget> createState() => _StemNoteWidgetState();
}

class _StemNoteWidgetState extends State<StemNoteWidget> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据
  late List<NoteVoModel> _list;

  /// 是否显示更多按钮
  late bool _showGd;

  @override
  void initState() {

    super.initState();
    _list = [];
    _showGd = false;
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        _titleItem(),
        hiSpace(height: 32),
        _futureItem(),
      ],
    );
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      ResourcePageModel<NoteVoModel> page = await SubjectDao.getNoteList(
        current: 1,
        size: 5,
        questionId: widget.qId,
      );
      if (page.records != null) {
        _list = page.records!;
        setState(() {
          _showGd = true;
        });
      }
      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 标题组件
  _titleItem() {
    return Row(

      children: [
        SvgPicture.asset(
          "images/question/stem_node.svg",
          width: 36,
          height: 29,
        ),
        SizedBox(width: 5,),
        Expanded(child: Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            if (_showGd)
              _showContainer(
                onTapFun: _onTapFunGd,
                widget: _gdNodeItem(),
              ),

            _showContainer(
              onTapFun: _onTapFunAdd,
              widget: _addNodeItem(),
            ),
          ],
        ))
        ,
      ],
    );
  }

  /// 组件显示标签
  _showContainer({required Function() onTapFun, required Widget widget}) {
    return GestureDetector(
      onTap: onTapFun,
      child: Container(
        width: 100,
        height: 48,
        decoration: BoxDecoration(
          color: getColorBlue2(szYjms: szUtilComm.szInfo.yjms),
          borderRadius: BorderRadius.all(Radius.circular(24)),
        ),
        child: widget,
      ),
    );
  }

  /// 更多笔记组件
  _gdNodeItem() {
    return Center(
      child: Text(
        "更多",
        style: FontUtil.fontBlue1(18, szYjms: szUtilComm.szInfo.yjms),
      ),
    );
  }

  /// 添加笔记组件
  _addNodeItem() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SvgPicture.asset(
          "images/question/stem_node_icon.svg",
          width: 20,
          height: 20,
          color: getColorBlue1(szYjms: szUtilComm.szInfo.yjms),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 5),
          child: Text(
            "记笔记",
            style: FontUtil.fontBlue1(18, szYjms: szUtilComm.szInfo.yjms),
          ),
        ),
      ],
    );
  }

  /// 加载组件
  _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder:
          (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return SizedBox(
            height: 100,
            child: const Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
      },
    );
  }

  /// 内容显示方法
  _content() {
    if (_list.isNotEmpty) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: _listItems(),
      );
    } else {
      return SizedBox(
        height: 100,
        child: Text(
          "暂无",
          style: FontUtil.fontBlack1(
            szUtilComm.szInfo.getZtdxPx()!,
            szYjms: szUtilComm.szInfo.yjms,
          ),
        ),
      );
    }
  }

  /// 内容显示
  _listItems() {
    List<Widget> list = [];
    for (int i = 0; i < _list.length; i++) {
      NoteVoModel voModel = _list[i];
      list.add(NoteItemWidget(
        createName: voModel.createName,
        createHeader: voModel.createHeader,
        content: voModel.content,
        contentStyle: FontUtil.fontBlack1(
          szUtilComm.szInfo.getZtdxPx()!,
          szYjms: szUtilComm.szInfo.yjms,
        ),
      ));
      if (i != _list.length - 1) {
        list.add(hiSpace(height: 20));
      }
      if (i >= 1) {
        break;
      }
    }
    return list;
  }

  /// 添加方法
  void _onTapFunAdd() {
    _showPopupAdd();
  }

  /// 你点击了更多
  _onTapFunGd() {
    _showPopupList();
  }

  /// 显示添加的弹出层
  _showPopupAdd() async {
    showModalBottomSheet<int>(
      context: _context,
      // 设置底部弹出框全屏显示
      isScrollControlled: true,
      // 点击遮罩层是否可以关闭
      // isDismissible: false,
      // 自定义弹出层高度
      // constraints: BoxConstraints(maxHeight: 408),
      // 自定义圆角
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      builder: (context) {
        return SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            child: NoteAddWidget.question(
              relationId: widget.relationId,
              relationName: widget.relationName,
              qId: widget.qId,
              stem: widget.stem,
              type: widget.type,
            ),
          ),
        );
      },
    );
  }

  /// 显示更多的弹出层
  _showPopupList() async {
    // 获取弹出层高度
    var height = MediaQuery.of(_context).size.height;
    double sheetHeight = height * 0.8;
    showModalBottomSheet<int>(
      context: _context,
      // 设置底部弹出框全屏显示
      isScrollControlled: true,
      // 自定义弹出层高度
      constraints: BoxConstraints(maxHeight: sheetHeight),
      // 自定义圆角
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      builder: (context) {
        return NoteListWidget(
          qId: widget.qId,
          relationId: widget.relationId,
        );
      },
    );
  }
}
